//
//  PictureSelectorViewController.swift
//  SinaWeibo
//
//  Created by 周小伟 on 16/8/24.
//  Copyright © 2016年 周小伟. All rights reserved.
//

import UIKit

private let reuseIdentifier = "Cell"
private let column:CGFloat = 4
private let pictureCellMargin:CGFloat = 10

private let maxImageCount = 3

class PictureSelectorViewController: UICollectionViewController {
    lazy var imageList = [UIImage]()
    init(){
        let layout = UICollectionViewFlowLayout()
        let w = (screenW - (column + 1) * pictureCellMargin )/column
        layout.itemSize = CGSize(width: w, height: w)
        layout.minimumInteritemSpacing = pictureCellMargin
        layout.minimumLineSpacing = pictureCellMargin
        
        layout.sectionInset = UIEdgeInsets(top: pictureCellMargin, left: pictureCellMargin, bottom: 0, right: pictureCellMargin)
        
        super.init(collectionViewLayout: layout)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.collectionView?.registerClass(PictureSelectorCell.self, forCellWithReuseIdentifier: reuseIdentifier)
    }
    
    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        let delta = (imageList.count == maxImageCount) ? 0 : 1
        return delta + imageList.count
    }
    
    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! PictureSelectorCell
        cell.selectorCellDelegate = self
        cell.backgroundColor = UIColor.randomColor()
        
        if indexPath.item == imageList.count{
            cell.image = nil
        }else{
            cell.image = imageList[indexPath.item]
        }
        return cell
    }
}

extension PictureSelectorViewController:PictureSelectorCellDelegate{
    func userWillAddPicture(cell:PictureSelectorCell){
        if cell.image != nil{
            print("已经添加图片")
            return
        }
        
        print("添加图片")
        
        let picker = UIImagePickerController()
        
        picker.delegate = self
        
        presentViewController(picker, animated: true, completion: nil)
    }
    
    func userWillDeletePicture(cell:PictureSelectorCell){
        let indexPath = collectionView?.indexPathForCell(cell)
        self.imageList.removeAtIndex(indexPath!.item)
        
        UIView.animateWithDuration(0.5, animations: { 
            cell.alpha = 0
            }) { (_) in
                cell.alpha = 1
                self.collectionView?.reloadData()
        }
    }
}

extension PictureSelectorViewController:UIImagePickerControllerDelegate,UINavigationControllerDelegate{
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        imageList.append(image)
        collectionView?.reloadData()
        dismissViewControllerAnimated(true, completion: nil)
    }
}

@objc protocol PictureSelectorCellDelegate:NSObjectProtocol{
    optional func userWillAddPicture(cell:PictureSelectorCell)
    optional func userWillDeletePicture(cell:PictureSelectorCell)
}

class PictureSelectorCell: UICollectionViewCell {
    
    weak var selectorCellDelegate:PictureSelectorCellDelegate?
    @objc private func addBtnDidClick(){
        selectorCellDelegate?.userWillAddPicture?(self)
    }
    @objc private func deleteBtnDidClick(){
        selectorCellDelegate?.userWillDeletePicture?(self)
    }
    
    var image:UIImage?{
        didSet{
            deleteBtn.hidden = (image == nil)
            if image != nil{
                addBtn.setBackgroundImage(image, forState: .Normal)
            }else{
                addBtn.setBackgroundImage(UIImage(named: "compose_pic_add"), forState: .Normal)
            }
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:has not been implemented)")
    }
    
    private func setupUI(){
        contentView.addSubview(addBtn)
        contentView.addSubview(deleteBtn)
        addBtn.snp_makeConstraints { (make) in
            make.edges.equalTo(contentView.snp_edges)
        }
        
        deleteBtn.snp_makeConstraints { (make) in
            make.top.right.equalTo(contentView)
        }
        
        addBtn.addTarget(self, action: #selector(PictureSelectorCell.addBtnDidClick), forControlEvents: .TouchUpInside)
        deleteBtn.addTarget(self, action: #selector(PictureSelectorCell.deleteBtnDidClick), forControlEvents: .TouchUpInside)
    }
    private lazy var addBtn = UIButton(title: nil, backImage: "compose_pic_add", color: nil)
    
    private lazy var deleteBtn = UIButton(title: nil, backImage: "compose_photo_close", color: nil)
}
